<?php
/*
 * Index Page
*
*
*/
class Orthographe_WordCounter_IndexController extends Mage_Core_Controller_Front_Action
{
	public function indexAction()
	{
		$id  = $this->getRequest()->getParam('id');
		$email = $this->getRequest()->getParam('email');
		$refcmd = $this->getRequest()->getParam('refcmd');
		// 		echo "affiche le formulaire !!! ID = {$id}";

		Mage::log("NPL -  ".get_class($this)." - Affichage du formulaire {$id} / e: {$email} / ref: {$refcmd}",Zend_Log::DEBUG);

		// 		var_dump($this->getRequest()->getPost());

		$this->loadLayout();
		$this->_initLayoutMessages('customer/session');

		$this->renderLayout();
	}
	public function mamethodeAction()
	{
		echo 'test mamethode';
	}

	/**
	 * Url d'Upload du document
	 */
	public function uploadAction(){

		$post = $this->getRequest()->getPost();
		if ($post) {

			Mage::log("NPL -  ".get_class($this)."- Try to download a file from order {$post['id']}",Zend_Log::INFO);
// 			var_dump($post);

				
			Mage::app()->getRequest()->setParam('id', trim($post['id']));
			Mage::app()->getRequest()->setParam('email', trim($post['email']));
			Mage::app()->getRequest()->setParam('refcmd', trim($post['refcmd']));
				
			try {
				$postObject = new Varien_Object();
				$postObject->setData($post);

				$error = false;

				if (!Zend_Validate::is(trim($post['id']) , 'NotEmpty')) $error = true;
				$validator = new Zend_Validate_Int();
				if(!$validator->isValid(trim($post['id']))) $error = true;

				if (!Zend_Validate::is(trim($post['email']) , 'NotEmpty')) $error = true;
				$emailValidator = new Zend_Validate_EmailAddress();
				if(!$emailValidator->isValid(trim($post['email']))) $error=true;

				if (!Zend_Validate::is(trim($post['refcmd']) , 'NotEmpty')) $error = true;
				$validator = new Zend_Validate_Digits();
				if(!$validator->isValid(str_ireplace("#", "", trim($post['refcmd'])))) $error = true;


				if ($error) throw new Exception();


				$model = Mage::getSingleton('wordcounter/ajuste_quote_item')->load(trim($post['id']));
				if(!empty($model) || $model->getActive()){

					$refCmd=str_ireplace("#", "", trim($post['refcmd']));

					$validator = new Zend_Validate_Identical($refCmd);
					if($validator->isValid($model->getOrderItemNum())){
						//Model + Ref commande identique
						//Test l'email de la commande

						$order = Mage::getModel('sales/order')->load($model->getOrderItemNum(),'increment_id');
						$validator = new Zend_Validate_Identical(trim($post['email']));
						if($validator->isValid($order->getCustomerEmail())){
							Mage::log("NPL -  ".get_class($this)." - Upload possible du fichier revu pour la commande {$model->getId()}",Zend_Log::INFO);

							try {
								$this->_sendFile($model->getClientReviewFile(),$model->getClientReviewFilename());

								Mage::log("NPL -  ".get_class($this)." - Upload du fichier revu pour la commande {$model->getId()} OK",Zend_Log::INFO);

								$model->setDownloaded(true);
								//Update lastupdate
								Mage::helper('orthographewordcounter')->formatHistoricDBHistoric($model,$this->__('Review file downloaded with success')." order {$model->getId()}");

								// 								$model->setHistoric($model->getHistoric()+Mage::helper('orthographewordcounter')->formatHistoricDBHistoric($this->__('Review file downloaded with success')));
								Mage::log("NPL -  ".get_class($this)." - Histo new = {$model->getHistoric()}",Zend_Log::DEBUG);
								
								$model->setLastUpdate(time());
								$model->save();

								Mage::getSingleton('core/session')->addSuccess(Mage::helper('orthographewordcounter')->__('Sucess, client upload done'));
// 								$this->_redirect('*/*/index/id/'.$post['id']);
// 								return;
								
								//TODO
								// 								$this->_redirect('*/*/');
								// 								exit(0);
							} catch (Mage_Core_Exception $e) {
								Mage::log("NPL -  ".get_class($this)." - Error while downloading Review File for Command #{$id} ".$e->getMessage(),Zend_Log::ERR);
								$this->_getSession()->addError(Mage::helper('orthographewordcounter')->__('Sorry, there was an error getting requested content. Please contact the store owner.'));
								$this->_redirect('*/*/index/id/'.$post['id']);
								return;
							}



						}else{
							Mage::log("NPL -  ".get_class($this)." - Upload error not a valid email {$post['email']} is not a equal with the one in order id : {$post['id']} / {($order->getCustomerEmail()}",Zend_Log::DEBUG);
							Mage::getSingleton('core/session')->addError(Mage::helper('orthographewordcounter')->__('Sorry, there was an error getting requested content. Please contact the store owner.'));
							$this->_redirect('*/*/index/id/'.$post['id']);
							return;
						}

					} else {
						Mage::log("NPL -  ".get_class($this)." - Upload error ref command {$refCmd} is not a equal with the one in order id : {$post['id']} / {$model->getOrderItemNum()}",Zend_Log::DEBUG);

						Mage::getSingleton('core/session')->addError(Mage::helper('orthographewordcounter')->__('Error, ref not valid'));
						$this->_redirect('*/*/index/id/'.$post['id']);
						return;
					}


				}else{
					Mage::log("NPL -  ".get_class($this)." - Upload error no active order with id : {$post['id']}",Zend_Log::DEBUG);
						
					Mage::getSingleton('core/session')->addError(Mage::helper('orthographewordcounter')->__('Error, order not found'));
					$this->_redirect('*/*/index/id/'.$post['id']);
					return;
				}


			} catch (Exception $e) {

				Mage::log("NPL -  ".get_class($this)." - Upload error while validating data posted for order ID {$post['id']} : ".print_r($validator->getMessages(),true),Zend_Log::DEBUG);


				Mage::getSingleton('customer/session')->addError(Mage::helper('orthographewordcounter')->__('Error, upload post data'));
				$this->_redirect('*/*/index/id/'.$post['id']);
				return;
			}

		} else {
			$this->_redirect('*/*/');
		}


		$this->loadLayout();
		// 		$this->_initLayoutMessages('customer/session');
		$this->renderLayout();

		// 		$this->getResponse()->setRedirect($this->getUrl('*/*/'));
	}

	/**
	 * Send File to the Browser
	 * @param unknown $pdfPath
	 * @param string $filename
	 * @throws Exception
	 */
	protected function _sendFile($pdfPath,$filename=null) {
		if (! is_file ( $pdfPath ) || ! is_readable ( $pdfPath )) {
			throw new Exception ( );
		}
		$helper = Mage::helper('downloadable/download');
		$helper->setResource($pdfPath);
		Mage::log("NPL -  ".get_class($this)." - {$filename} -".filesize($pdfPath)." - {$pdfPath} ",Zend_Log::DEBUG);


		$this->getResponse ()
		->setHttpResponseCode ( 200 )
		->setHeader ( 'Pragma', 'public', true )
		->setHeader ( 'Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true )
		/* View in browser */
		//->setHeader ( 'Content-type', 'application/pdf', true )
		/*  Download */
		->setHeader ( 'Content-type', 'application/force-download',true )
		->setHeader ( 'Content-Length', filesize($pdfPath) );
		// 		->setHeader ('Content-Disposition', 'inline' . '; filename=' . basename($pdfPath) );
		if(empty($filename))
			$this->getResponse ()->setHeader ('Content-Disposition', 'inline' . '; filename=' . $helper->getFilename() );
		else
			$this->getResponse ()->setHeader ('Content-Disposition', 'inline' . '; filename=' . $filename );

		$this->getResponse ()->clearBody();
		$this->getResponse ()->sendHeaders ();
		readfile ( $pdfPath );
		//exit(0);
		// 		$helper->output();
	}

}